<?php

return function($oRes, $db_fadm, $class_token, $common_token) {
    if (empty($common_token)) {
        $this->error('请先登录');
    }
    $token_info = $class_token->TokenDecode($common_token);
    $field = 'user_id,UNIX_TIMESTAMP(actived)actived,token_json,error';
    $field .= ',login_ipaddr';
    $user_id = isset($token_info['user_id']) ? intval($token_info['user_id']) : 0;
    $mSession = $db_fadm->sql()->table('system_session')->where('user_id', $user_id)->field($field)->find();
    if (empty($mSession)) {
        $this->error('您的会话信息已被清除，请重新登录。', 401);
    }
    if (!empty($mSession['error'])) {
        $this->error($mSession['error']);
    }
    if (time() > $mSession['actived'] + 86400 * 30) {
        $this->error('会话已失效，请重新登录', 401);
    }
    $token_info_session = json_decode($mSession['token_json'], TRUE);
    if (empty($token_info_session)) {
        $this->error('无法解析token_json在user_session表', 401);
    }
    if (empty($token_info_session['logined']) || $token_info_session['logined'] !== $token_info['logined']) {
        $oRes->debug('token_user', $token_info);
        $oRes->debug('user_session', $mSession);
        $this->error('您的账号在别处登录', 401);
    }
    $oRes->setParam('mSession', $mSession);
};
